<?php
/**
 * Created by .
 * User: luogan
 * Date: 2021/12/23
 */

namespace app\admin\middleware;
use app\admin\service\AuthMenuService;
use app\admin\service\TokenService;

class AuthMiddleware
{
    //跳过验证token的url
    public static $token_ignore = ['v1/admin/login','/'];

    //跳过验证权限的url
    public static $auth_ignore = ['v1/admin/logout','v1/admin/admin_menu','v1/admin/admin_info'];

    public function handle($request, \Closure $next)
    {
        //跨域请求设置
        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Request-Method:POST");
        header("Access-Control-Allow-Headers:Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With");
        $currUrl = trim($request->url(), '/');
        if (in_array($currUrl, self::$token_ignore)) {
            return $next($request);
        }
        //验证token
        $payload = (new TokenService)->checkToken();
        if (in_array($currUrl, self::$auth_ignore)) {
            return $next($request);
        }
        //验证是否有访问菜单的权限
        (new AuthMenuService())->checkAuth($payload['admin_id'],$currUrl);
        return $next($request);
    }

}
